package com.ruoyi.patrol.controller;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.patrol.domain.PtAppVersion;
import com.ruoyi.patrol.service.PtAppVersionService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigInteger;
import java.security.MessageDigest;

/**
 * (PtAppVersion)表控制层
 *
 * @author elis
 * @since 2023-02-23 10:23:37
 */
@RestController
@RequestMapping("ptAppVersion")
public class PtAppVersionController {

    @Value("${upload.allPath}")
    private String uploadPrefix;

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 服务对象
     */
    @Resource
    private PtAppVersionService ptAppVersionService;

    /**
     * apk上传请求
     */
    @PostMapping("/app/upload")
    @PreAuthorize("@ss.hasPermi('app:add')")
    public AjaxResult appUploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath() + "/apk";
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.apkUpload(filePath, file);
            String url = uploadPrefix + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            // 文件MD5值
            // 文件本地存储路径
            String localFilePath = filePath + StringUtils.substring(fileName, (Constants.RESOURCE_PREFIX + "/upload/apk").length());
            File saveFile = new File(localFilePath);
            if (saveFile != null) {
                byte[] uploadBytes = FileUtils.readFileToByteArray(saveFile);
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                byte[] digest = md5.digest(uploadBytes);
                ajax.put("md5", new BigInteger(1, digest).toString(16));
            }
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取app最新版本
     */
    @GetMapping("/app/version/latest")
    public AjaxResult appUploadFile()
    {
        PtAppVersion appVersion = new PtAppVersion();
        appVersion.setLatest(1);
        return AjaxResult.success(ptAppVersionService.queryOne(appVersion));
    }

    /**
     * 分页查询
     *
     * @param
     * @param
     * @return 查询结果
     */
    @PreAuthorize("@ss.hasPermi('app:query')")
    @GetMapping("/list")
    public ResponseEntity<Page<PtAppVersion>> queryByPage(Integer page,Integer size) {
        return ResponseEntity.ok(this.ptAppVersionService.queryByPage(PageRequest.of(Convert.toInt(page-1),Convert.toInt(size))));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @PreAuthorize("@ss.hasPermi('app:query')")
    @GetMapping("{id}")
    public ResponseEntity<PtAppVersion> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(this.ptAppVersionService.queryById(id));
    }

    @PreAuthorize("@ss.hasPermi('app:edit')")
    @GetMapping("/new/{id}")
    public ResponseEntity<Boolean> setNew(@PathVariable Integer id) {
        return ResponseEntity.ok(this.ptAppVersionService.setNew(id));
    }

    @PreAuthorize("@ss.hasPermi('app:edit')")
    @GetMapping("/old/{id}")
    public ResponseEntity<Boolean> setOld(@PathVariable Integer id) {
        return ResponseEntity.ok(this.ptAppVersionService.setOld(id));
    }

    /**
     * 新增数据
     *
     * @param ptAppVersion 实体
     * @return 新增结果
     */
    @PreAuthorize("@ss.hasPermi('app:add')")
    @PostMapping("/add")
    public ResponseEntity<PtAppVersion> add(@RequestBody PtAppVersion ptAppVersion) {
        return ResponseEntity.ok(this.ptAppVersionService.insert(ptAppVersion));
    }

    /**
     * 编辑数据
     *
     * @param ptAppVersion 实体
     * @return 编辑结果
     */
    @PreAuthorize("@ss.hasPermi('app:edit')")
    @PutMapping
    public ResponseEntity<PtAppVersion> edit(PtAppVersion ptAppVersion) {
        return ResponseEntity.ok(this.ptAppVersionService.update(ptAppVersion));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @PreAuthorize("@ss.hasPermi('app:del')")
    @GetMapping("/del/{id}")
    public ResponseEntity<Boolean> deleteById(@PathVariable Integer id) {
        return ResponseEntity.ok(this.ptAppVersionService.deleteById(id));
    }

}

